package com.erpoa.aop;

import com.erpoa.annotation.DataBase;
import com.erpoa.multiple.DatabaseContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * @description:
 * @author: jamin.chen
 * @createDate: 2020/1/9 14:32
 * @version: 1.0
 */
@Aspect
@Component
public class DataSourceAspect implements Ordered{

    @Pointcut("@annotation(com.erpoa.annotation.DataBase)")//注意：这里的xxxx代表的是上面public @interface DataSource这个注解DataSource的包名
    public void dataSourcePointCut() {

    }

    @SuppressWarnings("rawtypes")
    @Before("dataSourcePointCut()")
    public void beforeSwitchDS(JoinPoint point){
        //获得当前访问的class
        Class<?> className = point.getTarget().getClass();
        //获得访问的方法名
        String methodName = point.getSignature().getName();
        //得到方法的参数的类型
        Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();

        String dataSource = DatabaseContextHolder.ERP;
        try {
            // 得到访问的方法对象
            Method method = className.getMethod(methodName, argClass);

            // 判断是否存在@DateBase注解
            if (method.isAnnotationPresent(DataBase.class)) {
                DataBase annotation = method.getAnnotation(DataBase.class);
                // 取出注解中的数据源名
                dataSource = annotation.value();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 切换数据源
        DatabaseContextHolder.setDatabaseType(dataSource);
    }


    @After("dataSourcePointCut()")
    public void afterSwitchDS(JoinPoint point){
        DatabaseContextHolder.clearDataSource();
    }


    @Override
    public int getOrder() {
        return 1;
    }
}
